package com.qf.web.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.upload.config.OSSConfigProperties;
import com.qf.web.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service
public class UploadServiceImpl implements UploadService {
    public static final String IMG_PREFIX_FILE="IMG_";
    public static final String DATE_FORMATE = "yyyyMMddHHmmss";
    public static final String DEFAULT_BUCKET_NAME_IMAGE = "image";
    public static final String END_Match = ".jpg";
    @Resource
    private OSS oss;

    @Resource
    private OSSConfigProperties properties;

    @Override
    public String uploadImage(MultipartFile multipartFile, String bucketName) {
        //使用传入的前缀去存储
        bucketName = bucketName==null?DEFAULT_BUCKET_NAME_IMAGE:bucketName;
        //获取源文件名字
        String filename = multipartFile.getOriginalFilename();
        //判断源文件是否为上传格式
        if (!filename.endsWith(END_Match)){
            //抛出不是图片格式异常
            throw new ServiceException(ResultCode.SMS_CODE_ERROR);
        }
        //获取新名字
        String newName = renameImg(filename);
        //照片储存的路径和照片新名
        String path = bucketName+"/"+DateUtil.format(new DateTime(),"yyyy-MM-dd")+"/"+ newName;
        try {
            //上传到阿里云
            PutObjectResult putObjectResult = oss.putObject(properties.getBucketName(), path, multipartFile.getInputStream());
            if (!ObjectUtil.isEmpty(putObjectResult.getETag())){
                //上传成功
                String url = getUrl(properties.getBucketName(), path);
                return url;
            }else {
                //抛出上传失败异常
                throw new ServiceException(ResultCode.SMS_CODE_ERROR);
            }
        } catch (IOException e) {
            //抛出上传失败异常
            throw new ServiceException(ResultCode.SMS_CODE_ERROR);
        }
    }

    //重命名图片
    public String renameImg(String filename){
        /**
         * 自定义命名规则 + 文件的后缀名
         * IMG_2022031415331234.png
         * ,,* xxxx.png
         */
        //获取原文件扩展名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String newname = String.format("%s%s%s%s", IMG_PREFIX_FILE, DateUtil.format(new DateTime(), DATE_FORMATE), RandomUtil.randomNumbers(4), suffixName);
        return newname;
    }

    private String getUrl(String bucketName, String key) {
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        String url = oss.generatePresignedUrl(bucketName, key, expiration).toString();
        return url;
    }
}
